// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: packimports(3) 
// Source File Name:   WorksetMap.java

package com.sapportals.portal.navigation;

import com.sapportals.common.PPLogger;
import com.sapportals.common.TracingConsts;
import com.sapportals.htmlb.*;
import com.sapportals.htmlb.enum.*;
import com.sapportals.htmlb.rendering.IPageContext;
import com.sapportals.htmlb.rendering.PageContextFactory;
import com.sapportals.portal.prt.component.*;
import com.sapportals.portal.prt.pom.INode;
import com.sapportals.portal.prt.runtime.IPortalRuntimeResources;
import com.sapportals.portal.prt.runtime.PortalRuntime;
import com.sapportals.portal.prt.service.IService;
import com.sapportals.portal.prt.service.IServiceContext;
import java.util.*;
import javax.naming.NamingException;
import javax.naming.directory.NoSuchAttributeException;

// Referenced classes of package com.sapportals.portal.navigation:
//            NavigationEventsHelperService, INavigationNamingHandler, INavigationMimeRepositoryService, INavigationService, 
//            INavigationNode, NavigationNodes, NavigationEventsHelper

public class WorksetMap extends AbstractPortalComponent
{

    public WorksetMap()
    {
        mm_logger = new PPLogger("/Server", "com.sap.portal.navigation");
    }

    public void doContent(IPortalComponentRequest request, IPortalComponentResponse response)
    {
        mm_logger.trace(TracingConsts.PATH, "WorksetMap.doContent", "Start doContent");
        INavigationNode navigationNode = null;
        NavigationNodes nodes = null;
        StringBuffer scriptTarget = null;
        NavigationEventsHelperService service = (NavigationEventsHelperService)PortalRuntime.getRuntimeResources().getService("com.sap.portal.navigation.helperservice.navigation_events_helper");
        INavigationNamingHandler navService = (INavigationNamingHandler)PortalRuntime.getRuntimeResources().getService("com.sap.portal.navigation.service.navigation");
        NavigationEventsHelper helper = service.getNavigationEventsHelperInstance();
        INavigationMimeRepositoryService mimeRepositoryService = (INavigationMimeRepositoryService)PortalRuntime.getRuntimeResources().getService("com.sap.portal.navigation.mimeservice.navigation_mime_repository");
        IPortalComponentContext componentContext = request.getComponentContext();
        IPortalComponentProfile profile = componentContext.getProfile();
        navigationNode = service.getCurrentLaunchNavNode(request);
        if(navigationNode == null)
            return;
        String navCompName = navigationNode.getName();
        navCompName = service.getInternalURL(navCompName);
        mm_logger.trace(TracingConsts.DEBUG, "WorksetMap.doContent", "Name of the workset map iView: {0}", navCompName);
        String worksetComp = navigationNode.getName();
        if(navigationNode.getVisualizationType() != 2)
        {
            String relativeWorksetPath = profile.getProperty("overviewCompName");
            worksetComp = buildNavigationTargetFromRelative(request, navService, service, navigationNode.getName(), relativeWorksetPath);
        }
        String mimeServiceCompName = ((IService)mimeRepositoryService).getContext().getApplicationName();
        String webResource = request.getWebResourcePath(mimeServiceCompName);
        INode currentNode = request.getNode();
        request.setNode(request.getNode().getParentNode());
        String parentName = null;
        if(request.getComponentContext() != null)
        {
            parentName = request.getComponentContext().getContextName();
            parentName = service.getInternalURL(parentName);
        }
        request.setNode(currentNode);
        response.write("<SCRIPT>");
        response.write("function openURL(eventObj) {");
        response.write("EPCM.doNavigate(eventObj); ");
        response.write("}");
        response.write("</SCRIPT>");
        IPageContext myContext = PageContextFactory.createPageContext(request, response);
        com.sapportals.htmlb.Form myForm = myContext.createFormDocument("overviewCompName");
        myContext.getDocument().addComponent(myForm);
        if(worksetComp == null)
        {
            Document myDocument = myContext.createDocument("RelativePathNotValid");
            addErrorMessageBar(request, response, myDocument);
            myContext.render(myDocument);
            return;
        }
        try
        {
            if(worksetComp.equals(""))
                worksetComp = navService.getNavNodeParentName(service.getEnvironment(request), navigationNode.getName());
            mm_logger.trace(TracingConsts.DEBUG, "WorksetMap.doContent", "Name of the Workset/Folder that is investigated: {0}", worksetComp);
            navigationNode = ((INavigationService)navService).getNode(service.getEnvironment(request), worksetComp);
            if(navigationNode != null)
            {
                nodes = getChildrenFromWorkset(request, service, navigationNode);
            } else
            {
                Document myDocument = myContext.createDocument("RelativePathNotValid");
                addErrorMessageBar(request, response, myDocument);
                myContext.render(myDocument);
                return;
            }
        }
        catch(Exception e)
        {
            mm_logger.traceThrowableT(TracingConsts.DEBUG, "WorksetMap.doContent: Cannot investigate workset/folder " + worksetComp, e);
        }
//Start Quack		
        int numOfNodes = nodes.size();
        mm_logger.trace(TracingConsts.DEBUG, "WorksetMap.doContent", "Found {0} children for workset {1}", String.valueOf(numOfNodes), worksetComp);
        FormLayout matrixLayout = new FormLayout();
        FormLayout worksetEntryLayout = new FormLayout();
        FormLayoutCell cell = null;
        FormLayoutCell imageCell = null;
        FormLayoutCell titleCell = null;
        FormLayoutCell descCell = null;
        com.sapportals.htmlb.ClientEventContainer eventContainer = null;
        TextView descTextView = null;
        INavigationNode currNode = null;
        Link titleLink = null;
        int currentPageLocation = -1;
        int k = 1;
        int middlePoint = numOfNodes % 2 != 0 ? numOfNodes / 2 + 1 : numOfNodes / 2;
        int i = 0;
        for(int j = 1; i < numOfNodes; j++)
        {
            currNode = (INavigationNode)nodes.get(i);
            if(currNode.getName().endsWith(navCompName) || parentName != null && currNode.getName().endsWith(parentName))
            {
                currentPageLocation = j;
                break;
            }
            i++;
        }

        if(currentPageLocation != -1 && numOfNodes % 2 == 1)
            middlePoint--;
        int i = 0;
        for(int j = 1; i < numOfNodes; j++)
        {
            currNode = (INavigationNode)nodes.get(i);
            if(j == currentPageLocation || k == 2 && middlePoint + j == currentPageLocation)
            {
                j--;
                currentPageLocation = -1;
            } else
            {
                if(j > middlePoint)
                {
                    j = 1;
                    k = 2;
                }
                worksetEntryLayout = new FormLayout();
                boolean enablePictogramClick = false;
                Image image = null;
                String enablePicClickProperty = profile.getProperty("enablePictogramClick");
                if(enablePicClickProperty != null)
                    enablePictogramClick = Boolean.valueOf(enablePicClickProperty).booleanValue();
                String imageName = null;
                try
                {
                    imageName = (String)currNode.getAttributeValue("com.sapportals.portal.navigation.Pictogram");
                    if(imageName == null || imageName.equals(""))
                        imageName = "default.gif";
                }
                catch(Exception e)
                {
                    imageName = "default.gif";
                }
                image = new Image(webResource + "/images/" + imageName, imageName);
                image.setTooltip(currNode.getTitle(request.getLocale()));
                if(enablePictogramClick)
                {
                    String nameImgLink = currNode.getName() + "imageLinkToNode";
                    Link imageLink = new Link(nameImgLink, "");
                    scriptTarget = new StringBuffer();
                    String navContext = null;
                    if(isFolderLeaf(currNode))
                        navContext = currNode.getName();
                    helper.addClickEvent(currNode, scriptTarget, request, false, "ExecuteLocally=true", navContext);
                    imageLink.setReference("javascript:void(0)");
                    imageLink.setOnClientClick(scriptTarget.toString());
                    imageLink.setLinkDesign(LinkDesign.DRAGRELATE);
                    imageLink.setTooltip(getNLSString(request, "NAVIGATE_TO") + currNode.getTitle(request.getLocale()));
                    imageLink.addComponent(image);
                    imageCell = worksetEntryLayout.addComponent(1, 1, imageLink);
                } else
                {
                    imageCell = worksetEntryLayout.addComponent(1, 1, image);
                }
                imageCell.setRowspan(2);
                imageCell.setPaddingRight("25");
                imageCell.setPaddingLeft("5");
                imageCell.setVerticalAlignment(CellVAlign.TOP);
                try
                {
                    titleLink = new Link(currNode.getName(), currNode.getTitle(request.getLocale()));
                    scriptTarget = new StringBuffer();
                    helper.addClickEvent(currNode, scriptTarget, request, false, true, "ExecuteLocally=true", true);
                    titleLink.setReference("javascript:void(0)");
                    titleLink.setOnClientClick(scriptTarget.toString());
                    titleLink.setLinkDesign(LinkDesign.DRAGRELATE);
                    titleLink.setTooltip(currNode.getTitle(request.getLocale()));
                    descTextView = new TextView(currNode.getDescription(request.getLocale()));
                    descTextView.setWrapping(true);
                    titleCell = worksetEntryLayout.addComponent(1, 2, titleLink);
                    descCell = worksetEntryLayout.addComponent(2, 1, descTextView);
                    titleCell.setVerticalAlignment(CellVAlign.TOP);
                    titleCell.setHorizontalAlignment(CellHAlign.LEFT);
                    descCell.setVerticalAlignment(CellVAlign.TOP);
                    descCell.setHorizontalAlignment(CellHAlign.LEFT);
                    descCell.setWidth("100%");
                }
                catch(Exception e)
                {
                    mm_logger.traceThrowableT(TracingConsts.DEBUG, "WorksetMap.doContent: Cannot read the description field for entry " + currNode.getName(), e);
                    descTextView.setText("Description Error: " + e.getMessage());
                    descCell = worksetEntryLayout.addComponent(2, 1, new TextView());
                }
                worksetEntryLayout.setWidth("100%");
                worksetEntryLayout.setDebugMode(false);
                cell = matrixLayout.addComponent(j, k, worksetEntryLayout);
                cell.setPaddingLeft("5");
                cell.setPaddingTop("5");
                cell.setPaddingRight("25");
                cell.setPaddingBottom("5");
                cell.setVerticalAlignment(CellVAlign.TOP);
            }
            i++;
        }

        matrixLayout.setWidth("80%");
        matrixLayout.setDebugMode(false);
        myForm.addComponent(matrixLayout);
        myContext.render();
        mm_logger.trace(TracingConsts.PATH, "WorksetMap.doContent", "End Of doContent");
    }

    private String buildNavigationTargetFromRelative(IPortalComponentRequest request, INavigationNamingHandler namingHandler, NavigationEventsHelperService helperService, String baseNode, String relativeParam)
    {
        String levelsUp = null;
        String pathList = null;
        String list[] = null;
        int size = 0;
        String constructedName = null;
        StringTokenizer st = new StringTokenizer(relativeParam, ";");
        StringTokenizer singleParamToken = null;
        StringTokenizer pathListTokenizer = null;
        String param = null;
        String paramName = null;
        Vector tmpPathList = null;
        while(st.hasMoreElements()) 
        {
            param = st.nextToken();
            singleParamToken = new StringTokenizer(param, "=");
            paramName = singleParamToken.nextToken();
            if(paramName.equalsIgnoreCase("levelsup"))
                levelsUp = singleParamToken.nextToken();
            else
            if(paramName.equalsIgnoreCase("pathlist"))
            {
                pathList = singleParamToken.nextToken();
                tmpPathList = new Vector();
                if(pathList != null && !pathList.equals("") && pathList.charAt(0) == '{' && pathList.charAt(pathList.length() - 1) == '}')
                {
                    pathList = pathList.substring(1, pathList.length() - 1);
                    for(pathListTokenizer = new StringTokenizer(pathList, ","); pathListTokenizer.hasMoreElements(); tmpPathList.addElement(pathListTokenizer.nextToken()));
                    list = new String[tmpPathList.size()];
                    for(int i = 0; i < tmpPathList.size(); i++)
                        list[i] = (String)tmpPathList.elementAt(i);

                }
            }
        }
        try
        {
            if(levelsUp == null && list == null)
                levelsUp = "1";
            if(list != null)
                size = list.length;
            mm_logger.trace(TracingConsts.DEBUG, "WorksetMap.doContent", "buildNavigationTargetFromRelative: parameters: baseNode = " + baseNode + ", levelsUp = " + levelsUp + ", list.length = " + size);
            constructedName = namingHandler.composeName(helperService.getEnvironment(request), baseNode, Integer.parseInt(levelsUp), list);
        }
        catch(NamingException ne)
        {
            mm_logger.traceThrowableT(TracingConsts.DEBUG, "WorksetMap.buildNavigationTargetFromRelative: Fail to retrieve nav node: baseNode=" + baseNode + ", levelsup=" + levelsUp + ", listSize=" + size, ne);
            return null;
        }
        return constructedName;
    }

    private void addErrorMessageBar(IPortalComponentRequest request, IPortalComponentResponse response, Document myDocument)
    {
        MessageBar mb = new MessageBar("RelativePathNotValid");
        String errorMessage = getNLSString(request, "ERROR_MSG");
        mb.setMessageText(errorMessage);
        mb.setMessageType(MessageType.ERROR);
        myDocument.addComponent(mb);
    }

    private String getNLSString(IPortalComponentRequest request, String resource_key)
    {
        try
        {
            ResourceBundle bundle = request.getResourceBundle();
            if(bundle != null)
                return bundle.getString(resource_key);
            else
                return resource_key;
        }
        catch(MissingResourceException e)
        {
            return resource_key;
        }
    }

    private NavigationNodes getChildrenFromWorkset(IPortalComponentRequest request, NavigationEventsHelperService service, INavigationNode node)
        throws NamingException
    {
        java.util.Hashtable environment = service.getEnvironment(request);
        if(node.getMergeID() == null || node.getMergeID().equals(""))
            return node.getChildren(environment);
        NavigationNodes nodes = service.getNavNodesListForTarget(request, node);
        if(nodes != null)
        {
            if(nodes.size() > 0)
                return ((INavigationNode)nodes.get(nodes.size() - 1)).getChildren(environment);
            else
                return nodes;
        } else
        {
            return new NavigationNodes();
        }
    }

    private boolean isFolderLeaf(INavigationNode navigationNode)
    {
        Boolean isFolderLeaf = null;
        try
        {
            isFolderLeaf = (Boolean)navigationNode.getAttributeValue("com.sap.portal.navigation.IsLeaf");
            if(isFolderLeaf == null)
                isFolderLeaf = Boolean.FALSE;
        }
        catch(NoSuchAttributeException ex)
        {
            isFolderLeaf = Boolean.FALSE;
        }
        return isFolderLeaf.booleanValue();
    }

    static final String PADDING_SIZE = "5";
    static final String PADDING_SIZE_RIGHT = "25";
    static final char RELATIVE_PATHLIST_PREFIX = 123;
    static final char RELATIVE_PATHLIST_SUFFIX = 125;
    static final String RELATIVE_PATHLIST_DELIMITER = ",";
    static final String DEFAULT_PICTOGRAM = "default.gif";
    static final String COMP_NAME = "overviewCompName";
    static final String EMPTY_STRING = "";
    static final String ENABLE_PIC_CLICK = "enablePictogramClick";
    static final String NAVIGATE_TO = "NAVIGATE_TO";
    public static final String KEY_ERROR_MSG = "ERROR_MSG";
    public static final String SUFFIX_IMG_LINK = "imageLinkToNode";
    PPLogger mm_logger;
}
